package org.firebug.spring.cloud.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class AccessLogFilter extends ZuulFilter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public String filterType() {
		return FilterConstants.POST_TYPE;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		String method = request.getMethod();
		String uri = request.getRequestURI();
		String param = request.getQueryString();
		try {
			String requestBody = StreamUtils.copyToString(request.getInputStream(), Charset.forName("UTF-8"));
			logger.info(requestBody);
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			String responseBody = StreamUtils.copyToString(ctx.getResponseDataStream(), Charset.forName("UTF-8"));
			ctx.setResponseBody(responseBody);
			logger.info(responseBody);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}